package cn.gzsxt.interceptor;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.gzsxt.annotation.AdminSessionUpdate;
import cn.gzsxt.service.AdminService;

/**
 * 用于处理，修改数据后，用户及时更新信息
 * @author ranger
 *
 */
public class AdminSessionUpdateInterceptor implements HandlerInterceptor {
	

	@Autowired
	private AdminService adminService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		

		return true;
	}

	/**
	 * 执行方法执行后，执行不出异常才刷新管理员信息
	 * @param request
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		
		HandlerMethod handlerMethod=(HandlerMethod)handler;
		Method method = handlerMethod.getMethod();
		AdminSessionUpdate adminSessionUpdate = method.getDeclaredAnnotation(AdminSessionUpdate.class);
		if (adminSessionUpdate!=null) {
			HttpSession session = request.getSession();
			Map<String, Object> admin =(Map<String, Object>) session.getAttribute("admin");
			Map<String, Object> resultAdmin = adminService.loginAdmin(admin);
			session.setAttribute("admin", resultAdmin);
		}

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
